package com.example.moments.ssmemo.activity;

import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.sqlite.db.SimpleSQLiteQuery;
import androidx.sqlite.db.SupportSQLiteQuery;

import com.example.moments.R;
import com.example.moments.adapter.ProxyAdapter;
import com.example.moments.adapter.RvAdapter;
import com.example.moments.dao.BaseDao;
import com.example.moments.dao.CommentDao;
import com.example.moments.dao.ContentDao;
import com.example.moments.dao.LinkDao;
import com.example.moments.db.AppDatabase;
import com.example.moments.db.RoomUtil;
import com.example.moments.repository.Repository;
import com.example.moments.ssmemo.ContentData;
import com.example.moments.ssmemo.adapter.PengyouquanAdapter;
import com.example.moments.ssmemo.entity.Comment;
import com.example.moments.ssmemo.entity.CommentData;
import com.example.moments.ssmemo.entity.Content;
import com.example.moments.ssmemo.entity.Image;
import com.example.moments.ssmemo.entity.Like;
import com.example.moments.ssmemo.entity.LikeData;
import com.example.moments.ssmemo.entity.Link;
import com.example.moments.ssmemo.entity.LinkData;
import com.example.moments.starpMome.Moment;
import com.example.moments.utils.DrawUtil;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

import lombok.SneakyThrows;

//import androidx.appcompat.app.AppCompatActivity;
//import androidx.navigation.ui.AppBarConfiguration;
//import com.example.myapplication.MainActivity;
//import com.example.myapplication.NotificationMonitorActivity;
//import com.example.myapplication.R;
//import com.example.myapplication.SmsReadActivity;
//import com.example.myapplication.adapter.ProxyAdapter;
//import com.example.myapplication.adapter.RvAdapter;
//import com.example.myapplication.databinding.ActivityMainBinding;
//import com.example.myapplication.databinding.ActivityWechatMomentsBinding;
//import com.example.myapplication.databinding.NotificationMonitorBinding;
//import com.example.myapplication.model.Moment;
//import com.example.myapplication.model.ShortMessage;
//import com.example.myapplication.observer.SMSContentObserver;
//import com.example.myapplication.util.DateUtil;
//import com.example.myapplication.util.DrawUtil;
//import com.example.myapplication.util.EmailSendThread;
//import com.google.android.material.snackbar.Snackbar;

public class MomentsActivity extends AppCompatActivity {
    //    private ActivityMainBinding binding;
//    private NotificationMonitorBinding
    private RecyclerView rv;
    private static final String TAG = "MomentsActivity";
//    private AppBarConfiguration appBarConfiguration;

    //    private RvAdapter rvAdapter;
    private PengyouquanAdapter rvAdapter;

//    private ActivityWechatMomentsBinding binding;

    private RecyclerView.ItemDecoration itemDecoration;

    @SneakyThrows
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        setButton();
//        setContentView(R.layout.activity_wechat_moments);
        setContentView(R.layout.activity_wechat_moments_ss);
//        binding = ActivityWechatMomentsBinding.inflate(getLayoutInflater());
//        setContentView(binding.getRoot());
//        setSupportActionBar(binding.toolbar);
//
//        setSupportActionBar(binding.toolbar);

        rv = findViewById(R.id.rv);
//        setDatas();
//        Log.i(TAG," setDatas");
//        Log.i(TAG, String.valueOf(datas));

//        不设置的话 就不显示了
        /**第一步：设置布局管理器**/
        rv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        /**第二步：添加分割线**/
        itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        rv.addItemDecoration(itemDecoration);
//        R.

        /**第三步：设置适配器**/
//        rvAdapter = new RvAdapter((Context) this, datas);
//        rvAdapter = new RvAdapter(this, datas);
//        这里还没有数据 要紧吗
        rvAdapter = new PengyouquanAdapter(this, datas);
//        AppCompatActivity 不是Context
//        rvAdapter = new RvAdapter(this.btn_add.getContext(), datas);
//        rv.setAdapter(rvAdapter);
//        setAdapter 需要设置 他的 代理

//        rvAdapter.setOnItemClickListener(new RvAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClickListener(int position, Integer data) {
//                Toast.makeText(MomentsActivity.this, "点击了" + position, Toast.LENGTH_SHORT).show();
//            }
//        });

//        proxyAdapter = new ProxyAdapter(rvAdapter);
//        setHeader(rv);
//        rv.setAdapter(proxyAdapter);
        rv.setAdapter(rvAdapter);
//        设置 adapter 在 setHeader 里面

//          ivMyAvatar=findViewById(R.id.ivMyAvatar);
////          因为 没有header 的时候 是没有的
//        DrawUtil.setRoundImageDrawable(ivMyAvatar,R.drawable.miku_fang,getResources());
//        ivMyAvatar
//        setContentView(R.layout.activity_sms_read);

//        Comment comment = new Comment();
//        comment.se
//        comment.setContent();
        initDatabase();
//        mockDb();
//        repository.getContentDao().clearAll();
//        repository.getImageDao().clearAll();
//        repository.getCommentDao().clearAll();

        repository.getContentRepository().clearAll();
        repository.getImageRepository().clearAll();
        repository.getLinkRepository().clearAll();
        repository.getLikeRepository().clearAll();
        repository.getCommentRepository().clearAll();


        mockDb();


        initDataFromDb();
    }

    Repository repository;
//    ContentDao contentDao;
//    CommentDao commentDao;

    void initDatabase() {
//        database = AppDatabase.getDatabase(getApplicationContext());
//        contentDao = database.contentDao();
//        commentDao = database.commentDao();
//        Content content = new Content();
//        contentDao.insert()
        repository = new Repository();
//        repository.getContentDao().insert()

    }

    ImageView ivMyAvatar;
    //    List<Moment> datas = new ArrayList<>();
    List<ContentData> datas = new ArrayList<>();
    ProxyAdapter proxyAdapter;
    int lo_explore_pengyouquan_head_item = R.layout.explore_pengyouquan_head_item_starp;

    private AppDatabase database;

    private void setHeader(RecyclerView view) {
//        RecyclerView.Adapter adapter;
//        adapter.setHasStableIds();
//       int i= R.layout.explore_pengyouquan_head_item_starp;
//        View header = LayoutInflater.from(this).inflate(R.layout.explore_pengyouquan_head_item, view, false);
//        View header = LayoutInflater.from(this).inflate(R.layout.explore_pengyouquan_head_item_starp, view, false);
        View header = LayoutInflater.from(this).inflate(lo_explore_pengyouquan_head_item, view, false);
//        rvAdapter.set(header);
//        Adapter setheader
//        rvAdapter.add

//        R.id.
//       ContactAdapter adapter = new ContactAdapter();
        ivMyAvatar = header.findViewById(R.id.ivMyAvatar);
        DrawUtil.setRoundImageDrawable(ivMyAvatar, R.drawable.miku_fang, getResources());
//        DrawUtil.ad
//        ProxyAdapter proxyAdapter = new ProxyAdapter(rvAdapter);
        proxyAdapter.addHeaderView(header);
//        rv.setAdapter(proxyAdapter);

//        setAdapter 需要设置 他的 代理
//        https://www.cnblogs.com/canf963/p/7681608.html
//        为什么 etAdapter(proxyAdapter)
//        而 不是 原来的 rvAdapter，这样感觉 很复杂
//        adapter 单独的一个类

    }

    List<CommentData> mockCommentDatas() {
        List<CommentData> commentDatas = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
//               public CommentData(String username, String content, String replyUsername) {
            commentDatas.add(new CommentData("蜘蛛侠",
                    "你很强", "miku酱~"));
        }
        return commentDatas;
    }

    List<Integer> mockImgs() {
//        九宫格里面的图片
        List<Integer> images = new ArrayList<>();
//        List<CommentData> commentDatas=new ArrayList<>();
        for (int i = 0; i < 5; i++) {
//               public CommentData(String username, String content, String replyUsername) {
            images.add(R.drawable.miku_fang);
        }
        return images;
    }

    //    void toArr(List<T>){
//        Image [] imageArr=new Image[images.size()];
//        int idx=0;
//        for (Image image : images) {
//            imageArr[idx++]=image;
//        }
//    }
    void mockImgsDb(Long contentId) {

//        那么这是在循环里
        List<Image> images = new ArrayList<>();
        int siz=5;
        for (int i = 0; i < 5; i++) {
//               public CommentData(String username, String content, String replyUsername) {
//            images.add(R.drawable.miku_fang);
            Image image = new Image();
            image.setImg(R.drawable.miku_fang);
            image.setContentId(contentId);
            images.add(image);
//            图片好像没有显示啊啊
        }
//        java list 转化为 arr
//        https://blog.csdn.net/lpq374606827/article/details/93203927
//        Image [] imageArr=new Image[images.size()];
//        int idx=0;
//        for (Image image : images) {
//            imageArr[idx++]=image;
//        }
//        Image[] imageArr = (Image[]) images.toArray();

        Image[] imageArr = images.toArray(new Image[0]);
//        repository.getImageDao().insertAll(imageArr);
        repository.getImageRepository().insertAll(imageArr);
//        contentDao
//        im
//        return images;
//        repository.getImageRepository().
    }

    void mockContent() {
        Content[] contents = new Content[5];
        for (int i = 0; i < 5; i++) {
            Content content = new Content();
            content.setContent("这就是你的逃走线路吗");
            content.setUsername("miku酱~");
            contents[i] = content;
//            每个都有个 图片
//            必须插入才知道 id
        }
//        contentDao.insertAll(contents);
//        repository.getContentDao().insertAll(contents);
//        contentDao.insert(content);
        repository.getContentRepository().insertAll(contents);
    }

    void mockComments(Long contentId) {
        int siz=9;
        Comment[] comments = new Comment[siz];
        for (int i = 0; i < siz; i++) {
            Comment comment = new Comment();
            comment.setContent("好耶miku酱，白金之星，我起飞，我连宇宙的尽头都不知道，怎么会知道这种事");
            String username = "miku酱~";
            String replyUsername = "白金之星";
            comment.setUsername(username);
//            username 是说回复的人 还是背回复的人
            comment.setReplyUsername(replyUsername);
            comment.setContentId(contentId);
//            comment.setContent();
            comments[i] = comment;
//            每个都有个 图片
//            必须插入才知道 id
        }
//        contentDao.insertAll(contents);
//        repository.getContentDao().insertAll(contents);
//        repository.getCommentDao().insertAll(comments);
        repository.getCommentRepository().insertAll(comments);
    }

    void mockLinksDb(Long contentId) {
//        int siz=14;
//        Like[] likes = new Like[siz];
        Link link=new Link();
        link.setLinkImg(R.drawable.miku_fang);
        link.setLinkTitle("我连宇宙的尽头都不知道，怎么会知道这种事");
        link.setUrl("https://www.zhihu.com/people/yubozhou");
        link.setContentId(contentId);
        repository.getLinkRepository().insert(link);
//
//        for (int i = 0; i < siz; i++) {
//            Like like=new Like();
//            like.setContentId(contentId);
//
////            Comment comment = new Comment();
////            comment.setContent("好耶miku酱，白金之星，我起飞，我连宇宙的尽头都不知道，怎么会知道这种事");
//            String username = "miku酱~";
//            like.setUsername(username);
////            like.set(username);
//            String replyUsername = "白金之星";
////            comment.setUsername(username);
//////            username 是说回复的人 还是背回复的人
////            comment.setReplyUsername(replyUsername);
////            comment.setContentId(contentId);
//////            comment.setContent();
////            comments[i] = comment;
////            每个都有个 图片
////            必须插入才知道 id
//            likes[i]=like;
//        }
////        contentDao.insertAll(contents);
////        repository.getContentDao().insertAll(contents);
////        repository.getCommentDao().insertAll(comments);
////        repository.getCommentRepository().insertAll(comments);
//        repository.getLikeRepository().insertAll(likes);
    }

    
    void mockLikesDb(Long contentId) {
        int siz=14;
        Like[] likes = new Like[siz];
        for (int i = 0; i < siz; i++) {
            Like like=new Like();
            like.setContentId(contentId);

//            Comment comment = new Comment();
//            comment.setContent("好耶miku酱，白金之星，我起飞，我连宇宙的尽头都不知道，怎么会知道这种事");
            String username = "miku酱~";
            like.setUsername(username);
//            like.set(username);
            String replyUsername = "白金之星";
//            comment.setUsername(username);
////            username 是说回复的人 还是背回复的人
//            comment.setReplyUsername(replyUsername);
//            comment.setContentId(contentId);
////            comment.setContent();
//            comments[i] = comment;
//            每个都有个 图片
//            必须插入才知道 id
            likes[i]=like;
        }
//        contentDao.insertAll(contents);
//        repository.getContentDao().insertAll(contents);
//        repository.getCommentDao().insertAll(comments);
//        repository.getCommentRepository().insertAll(comments);
        repository.getLikeRepository().insertAll(likes);
    }


    void mockLike(){

    }


    void mockDb() throws ExecutionException, InterruptedException {
        mockContent();
//        每次开启 都往数据库写数据了 ，所以现在数据很多了
//        List<Content> contents = repository.getContentDao().getAll();
        List<Content> contents = repository.getContentRepository().getAll();
//        Log.i(TAG, "contents : "+contents);
        if(contents==null){
            return;
        }
        if(contents.size()<=0){
            return;
        }
        Log.i(TAG, "contents size : "+contents.size());
        Log.i(TAG, "contents get(0) : "+contents.get(0));
//        写入数据库 挺慢的 。。 就有时候他可能查出来都是空的 所以要做判断
//        这里数据有了
//        List<Content> contents = contentDao.getAll();
//        ContentData contentData
        for (Content content : contents) {
//            给他 img
            Long id = content.getId();
            mockImgsDb(id);
            mockComments(id);
            mockLikesDb(id);
            mockLinksDb(id);
        }
    }
    
    

    @RequiresApi(api = Build.VERSION_CODES.N)
    void initDataFromDb() throws ExecutionException, InterruptedException, IllegalAccessException {
//        List<Content> contents = repository.getContentDao().getAll();
//        List<Content> contents = repository.getContentDao().getAll();
        List<Content> contents = repository.getContentRepository().getAll();
//        SupportSQLiteQuery query=new SupportSQLiteQuery();
//        SimpleSQLiteQuery query = new SimpleSQLiteQuery("SELECT * FROM User WHERE id = ? LIMIT 1", new Object[]{userId});



        for (Content content : contents) {
            ContentData contentData = new ContentData();
            contentData.setContent(  content.getContent());
//            contentData.setContent(  content.getContent());
//            repository.getCommentDao().getAllByContentId()
//            List<Comment> allByContentId = repository.getCommentRepository().getAllByContentId(content.getId());
//            Comment.
            Long contentId = content.getId();
            Comment comment = new Comment();
            comment.setContentId(contentId);

            Log.i(TAG, "contentId : "+contentId);
//        CommentDao commentDao = repository.getCommentDao();
            List<Comment> comments = repository.getCommentRepository().selectBy(comment);
            Log.i(TAG, "comments : "+comments);
//        BaseDao<Comment> commentBaseDao = new BaseDao<>();
//        List<Comment> select = RoomUtil.select(commentDao, comment);

//            List<CommentData> list = CommentData.parseFromDbLst(allByContentId);
            List<CommentData> list = CommentData.parseFromDbLst(comments);
            Log.i(TAG, " List<CommentData> : "+list);

//            contentData.setCommentDatas(mockCommentDatas());
            contentData.setCommentDatas(list);


//            List<Image> images = repository.getImageDao().getAllByContentId(content.getId());
//            List<Image> images = repository.getImageRepository().getAllByContentId(content.getId());
            Image image = new Image();
            image.setContentId(contentId);
            List<Image> images = repository.getImageRepository().selectBy(image);
//            contentData.setImages(mockImgs());
            Log.i(TAG, " images : "+images);
            List<Integer> imgsInts = images.stream().map(Image::getImg).collect(Collectors.toList());
            contentData.setImages(imgsInts);
//                @RawQuery
//    List<T> getViaQuery(SupportSQLiteQuery query);
            initViewDataOfLike(contentData,contentId);
            initViewDataOfLink(contentData,contentId);
            datas.add(contentData);
        }
    }


    void initViewDataOfLink(ContentData contentData,Long  contentId)
            throws ExecutionException, InterruptedException {
        Link link=new Link();
        link.setContentId(contentId);
//        Like like = new Like();
//        like.setContentId(contentId);
//        List<Like> likes = repository.getLikeRepository().selectBy(like);
        List<Link> links = repository.getLinkRepository().selectBy(link);
//        LikeData likeData=new LikeData();
//        likeData.setUsername();
        if(links==null){
            return;
        }
        if(links.size()>=1){
//            List<LinkData> linkDatas = LinkData.toMe(links);
            LinkData linkData = LinkData.toMe(links.get(0));
//        List<LikeData> likeDatas = LikeData.toMe(likes);
//        contentData.setLikeData(likeDatas);
            contentData.setLinkData(linkData);
//            LinkData linkData;
//            linkData.setLinkimg(R.drawable.miku_fang);
//            linkData.setLinkimg(R.drawable.miku_fang);
        }

    }
    
    void initViewDataOfLike(ContentData contentData,Long  contentId)
            throws ExecutionException, InterruptedException {
        Like like = new Like();
        like.setContentId(contentId);
        List<Like> likes = repository.getLikeRepository().selectBy(like);
//        LikeData likeData=new LikeData();
//        likeData.setUsername();
        List<LikeData> likeDatas = LikeData.toMe(likes);
        contentData.setLikeData(likeDatas);
//        contentData.setLinkData();
//        LinkData linkData;
//        linkData.setLinkimg(R.drawable.miku_fang);
//        linkData.setLinkimg(R.drawable.miku_fang);
    }

    void setDatas() {
//        Resources resources = getResources();
//        Moment moment = new Moment();
//        Moment.builder().
//        Moment.buil
//        Moment moment1 = new Moment();
//        moment1.
//        Moment
//        for (int i = 0; i < 4; i++) {
////            new Moment(1,1);
//            Moment moment = new Moment();
//            moment.setId(i);
//            moment.setAvatar(R.drawable.miku_fang);
//            moment.setNickname("miku酱~");
//            moment.setWrittenwords("这就是你的逃走线路吗");
//            moment.setImgs("https://image.renlaibang.com/FiP9T9ncrNL-AH45IMhQaZgqwwSk,https://image.renlaibang.com/Fp5mQrZYnhSRoKayTsPEaBO18Wrt,https://image.renlaibang.com/Fv4GWEHOMvdMkBHz12XWxtEJMSd1,https://image.renlaibang.com/FgiOlNKk71GfgzunMvRXwi1zzIPp,https://image.renlaibang.com/FhAkT41j6Ma5wGRmYcm4MQF2NjSt,https://image.renlaibang.com/Fj8opkB-dS_Jmg-K41oWRhJQs0i0");
////            Moment moment = Moment.builder().id(i).
//////                    avatar(R.drawable.ic_launcher_foreground)
//////                    avatar(R.drawable.makima)
////                    avatar(R.drawable.miku_fang)
////                    .nickname("starp").writtenwords("这就是你的逃走线路吗").
////                            imgs("https://image.renlaibang.com/FiP9T9ncrNL-AH45IMhQaZgqwwSk,https://image.renlaibang.com/Fp5mQrZYnhSRoKayTsPEaBO18Wrt,https://image.renlaibang.com/Fv4GWEHOMvdMkBHz12XWxtEJMSd1,https://image.renlaibang.com/FgiOlNKk71GfgzunMvRXwi1zzIPp,https://image.renlaibang.com/FhAkT41j6Ma5wGRmYcm4MQF2NjSt,https://image.renlaibang.com/Fj8opkB-dS_Jmg-K41oWRhJQs0i0").build();
//            datas.add(moment);
//        }


//        List<Content> all = contentDao.getAll();
//        Comment comment = new Comment();
//        comment.setContentId();
//        commentDao.getAll();
//        commentDao.getAllByContentId();
//        for (Content content : all) {
//
//            ContentData contentData = new ContentData();
//            contentData.setContent(  content.getContent());
//            contentData.setContent(  content.getContent());
//            contentData.setCommentDatas(mockCommentDatas());
//            contentData.setImages(mockImgs());
//        }
//


        for (int i = 0; i < 4; i++) {
//            new Moment(1,1);
            ContentData contentData = new ContentData();
            contentData.setContent("这就是你的逃走线路吗");
//            Content content = new Content();
//            content.setContent("这就是你的逃走线路吗");
//            content.setUsername("miku酱~");
//            contentDao.insert(content);
//            List<CommentData> mockCommentDatas = mockCommentDatas();
//            for (CommentData mockCommentData : mockCommentDatas) {
////                mockCommentData.
//                Comment comment = new Comment();
////                comment.setContentId(contentData);
//            }

            contentData.setCommentDatas(mockCommentDatas());
            contentData.setImages(mockImgs());
//            contentData.set();
//
//            Moment moment = new Moment();
//            moment.setId(i);
//            moment.setAvatar(R.drawable.miku_fang);
//            moment.setNickname("miku酱~");
//            moment.setWrittenwords("这就是你的逃走线路吗");
//            moment.setImgs("https://image.renlaibang.com/FiP9T9ncrNL-AH45IMhQaZgqwwSk,https://image.renlaibang.com/Fp5mQrZYnhSRoKayTsPEaBO18Wrt,https://image.renlaibang.com/Fv4GWEHOMvdMkBHz12XWxtEJMSd1,https://image.renlaibang.com/FgiOlNKk71GfgzunMvRXwi1zzIPp,https://image.renlaibang.com/FhAkT41j6Ma5wGRmYcm4MQF2NjSt,https://image.renlaibang.com/Fj8opkB-dS_Jmg-K41oWRhJQs0i0");
//            Moment moment = Moment.builder().id(i).
////                    avatar(R.drawable.ic_launcher_foreground)
////                    avatar(R.drawable.makima)
//                    avatar(R.drawable.miku_fang)
//                    .nickname("starp").writtenwords("这就是你的逃走线路吗").
//                            imgs("https://image.renlaibang.com/FiP9T9ncrNL-AH45IMhQaZgqwwSk,https://image.renlaibang.com/Fp5mQrZYnhSRoKayTsPEaBO18Wrt,https://image.renlaibang.com/Fv4GWEHOMvdMkBHz12XWxtEJMSd1,https://image.renlaibang.com/FgiOlNKk71GfgzunMvRXwi1zzIPp,https://image.renlaibang.com/FhAkT41j6Ma5wGRmYcm4MQF2NjSt,https://image.renlaibang.com/Fj8opkB-dS_Jmg-K41oWRhJQs0i0").build();
            datas.add(contentData);
        }

    }


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

}
